package com.henushang.ranking.dao.impl;

import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.springframework.stereotype.Repository;

import com.henushang.ranking.dao.WebsiteInfoDao;
import com.henushang.ranking.domain.WebsiteInfo;
import com.henushang.ranking.util.mongo.MongoUtil;
import com.mongodb.client.MongoCollection;

@Repository("websiteInfoDao")
public class WebsiteInfoDaoImpl implements WebsiteInfoDao {

    private static String collectionName = "website_info";
    private static MongoCollection<WebsiteInfo> coll = null;

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    public boolean insert(WebsiteInfo websiteInfo) {

        return insertOne(websiteInfo);
    }

    public WebsiteInfo getOne(String _id) {

        return findOneById(_id);
    }

    public boolean delete(String _id) {

        return deleteById(_id);
    }

    public List<WebsiteInfo> getListByQueryMap(Map<String, Object> queryMap) {

        return findList(queryMap);
    }

    public boolean update(WebsiteInfo websiteInfo) {
        return updateById(websiteInfo);
    }

    @Override
    public MongoCollection<WebsiteInfo> getColl() {
        if (coll == null) {
            try {
                coll = MongoUtil.getColl(collectionName);
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        return coll;
    }

    @Override
    public Document toDocument(WebsiteInfo websiteInfo) {
        Document document = new Document();
        document.put("_id", websiteInfo.get_id());
        document.put("name", websiteInfo.getName());
        document.put("create_time", websiteInfo.getCreate_time());
        return document;
    }

    @Override
    public WebsiteInfo fromDocument(Document document) {

        WebsiteInfo info = new WebsiteInfo();
        if (document == null) {
            return info;
        }
        info.set_id(document.getString("_id"));
        info.setName(document.getString("name"));
        info.setCreate_time(document.getString("create_time"));
        return info;
    }

    public static void main(String[] args) {
        WebsiteInfoDao dao = new WebsiteInfoDaoImpl();
        String id = "001";
        WebsiteInfo info = new WebsiteInfo();
        info.set_id(id);
        info.setName("QQ");
        info.setCreate_time("2018-06-05 11:22:11");
        //        boolean re = dao.insert(info);
        //        System.out.println(re);
        WebsiteInfo info1 = dao.getOne(id);
        System.out.println(info1);
        info.setName("腾讯");
        dao.update(info);
        System.out.println(dao.getOne(id));
        //        boolean d = dao.delete(id);
        //        System.out.println(d);
    }
}
